/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

/**
 * 一个简单的 数据编辑 Grid
 *
 * @author vacoor
 */
Ext.define('Nothing.ux.grid.DataGrid', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.datagrid',
    minus: [],

    requires: [
        'Ext.ux.PagingToolbarResizer', 'Ext.ux.grid.FiltersFeature',
        'Ext.ux.grid.Printer', /*'Ext.grid.plugin.CellEditing',*/
        'Ext.grid.plugin.RowEditing', 'Ext.ux.form.SearchField',
        'Ext.ux.grid.FiltersFeature',
        'Ext.ux.grid.plugin.HeaderFilters'
    ],

    plugins: [/*'cellediting',*/ 'rowediting'/*, 'filterbar'*/,
        // getGridColumns(refreshCache) 没有这个方法了
        Ext.create('Ext.ux.grid.plugin.HeaderFilters')
    ],
    /*
    features: [{
        ftype: 'filters',
        store: 'Users',
        filters: [{
            type: 'string',
            dataIndex: 'username'
        }]
    }],
    */

    rownumbers: true, // 是否启用行号

    pagination: true,

    createEnabled: true,    // 是否启用新增

    editEnabled: true,      // 是否启用编辑

    deleteEnabled: true,    // 是否启用删除

    exportEnabled: true,    // 是否启用导出

    printEnabled: true,     // 是否启用打印

    quickEditEnabled: true,

    // ------
    createText: '新增',

    createCls: 'icon-add',

    editText: '编辑',

    editCls: 'icon-edit',

    deleteText: '删除',

    deleteCls: 'icon-delete',

    exportText: '导出',

    exportCls: 'icon-export',

    printText: '打印',

    printCls: 'icon-print',

    /*
     * 不要在配置中使用对象
     * 否则当grid销毁时, 该对象也会被销毁, 下次创建时依然引用该对象
     */
    //selModel: { selType: 'checkboxmodel' }, //Ext.create('Ext.selection.CheckboxModel'),
    selType: 'checkboxmodel',
    autoScroll: true,

    initComponent: function () {
        var me = this,
            tbar = [],
            re = me.findPlugin('rowediting');

        /*
         me.viewConfig= {
         enableTextSelection : true,
         loadMask : new Ext.LoadMask(this, {msg : '正在努力加载。。。'})//遮罩
         };
         */

        // column
        if (me.rownumbers) {
            me.columns = [
                { xtype: 'rownumberer', width: 50 }
            ].concat(me.columns);
        }

        Ext.each(['create', 'edit', 'delete', 'export', 'print'], function (act) {
            if (me[act + 'Enabled']) {
                me.addSeparatorItem(tbar, {
                    scope: me,
                    text: me[act + 'Text'],
                    iconCls: me[act + 'Cls'],
                    //handler: Ext.Function.bind(me['on' + Ext.String.capitalize(act)], me)
                    handler: me['on' + Ext.String.capitalize(act)] // 指定scope 和 bind一个样
                });
            }
        });

        me.addSeparatorItem(tbar, {
            scope: me,
            text: '快',
            enableToggle: true,
            pressed: me.quickEditEnabled,
            handler: function () {
                var me = this,
                    plugin = me.findPlugin('rowediting');
                plugin.setDisabled && plugin.isDisabled && plugin.setDisabled(!plugin.isDisabled());
            }
        });

        // TODO 这个时临时的
        me.addSeparatorItem(tbar, {
            scope: me,
            text: '同步',
            handler: function () {
                // mask
                this.store.sync();
            }
        });

        me.addSeparatorItem(tbar, {
            scope: me,
            text: '回滚',
            handler: function () {
                this.store.rejectChanges();
            }
        });

        me.tbar = tbar.concat(me.tbar || []);

        if (me.pagination) {
            me.bbar = [
                { xtype: 'pagingtoolbar', store: me.store }
            ].concat(me.bbar || []);
        }

        // rowediting
        if (re) {
            re.setDisabled(!me.quickEditEnabled);
            me.mon(re, 'beforeedit', Ext.Function.bind(me.updateTbarButtons, me, [true]), me);
            me.mon(re, 'edit', Ext.Function.bind(me.updateTbarButtons, me, [false]), me);
            me.mon(re, 'canceledit', Ext.Function.bind(me.updateTbarButtons, me, [false]), me);
        }

        me.callParent(arguments);
        me.getView().on('containerkeydown', me.onViewKeyDown, me);
        me.getView().on('cellkeydown', me.onViewKeyDown, me);
    },

    onViewKeyDown: function(view) {
        var me = this,
            evt = arguments[arguments.length - 1];

        if (!evt.altKey) {
            return;
        }

        if (evt.A == evt.keyCode) {
            me.onCreate();
            return;
        }

        if (evt.E == evt.keyCode) {
            me.onEdit();
            return;
        }
    },

    updateTbarButtons: function (disabled) {
        var me = this,
            buttons = me.down('toolbar').query('button');

        Ext.each(buttons, function (button, i) {
            button.setDisabled(disabled);
        });
    },

    // @private
    addSeparatorItem: function (items, item) {
        if (items.length % 2) {
            items.push('-');
        }

        items.push(item);
    },

    onCreate: function (button, evt) {
        var me = this,
            re = me.findPlugin('rowediting');

        if (re && !re.isDisabled()) {
            me.store.insert(0, {});
            re.startEdit(0, 0);
            window.re = re;
            re.getEditor().items.items[1].focus();
//            re.getEditor().focus();
        }
    },

    onEdit: function () {
        var me = this,
            re = me.findPlugin('rowediting'),
            selection = me.getSelectionModel().getSelection();

        if (selection.length != 1) {
            Ext.MessageBox.alert("消息", "只能选择一条");
            return;
        }

        if (re && !re.editing) {
            re.startEdit(selection[0], 0);
        }
    },

    onDelete: function (button, e) {
        var me = this,
            store = me.store,
            selection = me.getSelectionModel().getSelection();

        if (selection.length < 1) {
            Ext.MessageBox.alert("消息", "至少选择一条");
            return;
        }

        store.remove(selection);
        store.sync();
        // 为了保证当前页条数...
        // store.reload();
        store.loadPage(1);
    },

    onExport: function (button, e) {
        var me = this,
            store = me.store;
        store.exp();
    },


    onPrint: function (button, e) {
        var me = this;

        Ext.ux.grid.Printer.pageTitle = me.title || '';
        Ext.ux.grid.Printer.printAutomatically = true;
        Ext.ux.grid.Printer.print(me);
    }
});